var app = getApp()
var util = require("../../utils/util.js")
var tuanModel = require("../../model/tuanModel.js")
var timeUtil = require("../../utils/timeUtil.js")
var userUtil = require("../../utils/userUtil.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    share: 0, //是否通过分享进入
    success: 0, //是否成团
    remaining: [], //剩余位置
    timeStr: "00:00:00"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var id = options.trId
    this.setData({
      share: options.share ? 1 : 0,
      id: id
    })

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.init(this.data.id)
  },
  onUnload:function(){
    if(this.data.interval){
      clearInterval(this.data.interval)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var tuan = this.data.tuan
    var tr = this.data.tuanRecord
    return {
      title: this.data.tuan.productName,
      path: "/pages/tuan_join/tuan_join?share=1&trId=" + tr.id
    }
  },
  init(id) {
    var that = this
    tuanModel.getTuanInfo(id, res => {
      if (res.status == 1) {
        util.failToast(res.msg)
        return
      }
      var tuan = res.data.tuan
      var tr = res.data.tuanRecord
      tuan.discounts = (tuan.productPrice - tuan.price).toFixed(2)
      var customers = res.data.tuanCustomers
      var remaining = [] //剩余位置
      var len = tuan.people - customers.length
      var success = 0
      if (len > 0) {
        remaining[len - 1] = 0
      } else {
        success = 1
      }
      that.setData({
        tuan: tuan,
        tuanRecord: tr,
        customers: customers,
        remaining: remaining,
        success: success
      })
      if (success == 0) {
        if (that.data.interval)
          clearInterval(that.data.interval)
        var interval = timeUtil.countDown(tuan.validTime, res => {
          that.setData({
            timeStr: res
          })
          if(res=="00:00:00"){
            that.setData({
              success:1
            })
          }
        })
        that.setData({
          interval:interval
        })
      }
    })
  },
  //订单支付页面
  navToOrderPay(e) {
    if (!userUtil.isLogin()) {
      userUtil.toLogin()
      return
    }
    var type = parseInt(e.currentTarget.id)
    var tuan = this.data.tuan
    var goods = {
      id: tuan.productId,
      name: tuan.productName,
      price: tuan.price,
      imgUrl: tuan.productImgUrl,
      type: tuan.productType,
      num: 1
    }
    app.data.selectGoods = [goods]
    wx.navigateTo({
      url: '../order_pay/order_pay?type=2&tuanRecordId=' + this.data.tuanRecord.id + '&tuanId=' + tuan.id
    })
  },
  navToHome() {
    wx.reLaunch({
      url: '../nav_home/nav_home',
    })
  }
})